/*
 * @lc app=leetcode.cn id=496 lang=javascript
 *
 * [496] 下一个更大元素 I
 */

// @lc code=start
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var nextGreaterElement = function (nums1, nums2) {
  const stack = [];
  function size() {
    return stack.length;
  }
  function empty() {
    return size() === 0;
  }
  function peek() {
    if (empty()) {
      return undefined;
    }
    return stack[size() - 1];
  }
  function push(x) {
    stack.push(x);
  }
  function pop() {
    return stack.pop();
  }

  let res = {};
  for(let i = nums2.length - 1; i>= 0; i--) {
    const item = nums2[i];
    while (!empty() && item >= peek()) {
      pop();
    }
    res[item] = peek();
    push(item);
  }

  return new Array(nums1.length).fill(0).map((_, index) => res[nums1[index]] || -1)
};

// const test = [9, 6, -2, -8, 7, 5, 2, 3, -11];

// @lc code=end
